//
//  MeTableViewController.m
//  Hero
//
//  Created by lanou3g on 16/5/7.
//  Copyright © 2016年 刘永庆. All rights reserved.
//

#import "MeTableViewController.h"
#import "ChaXunViewController.h"
#import "YQLoginViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "SetUpTableViewController.h"
#define kWidth     [UIScreen mainScreen].bounds.size.width
#define kHeight    [UIScreen mainScreen].bounds.size.height
@interface MeTableViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation MeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSArray new];
    self.navigationController.navigationBar.backgroundColor = [UIColor brownColor];
    self.dataArray = @[@"召唤师查询",@"英雄数据",@"段位查询"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"myCell"];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 0.43, 40, 50, 50)];
    [view addSubview:imageView];
    NSFileManager *fileManger = [NSFileManager defaultManager];
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [document stringByAppendingPathComponent:@"image.png"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"auth"]) {
        if ([fileManger fileExistsAtPath:path]) {
            imageView.image = [UIImage imageWithContentsOfFile:path];
        }
        else{
            imageView.image = [UIImage imageNamed:@"占位图.png"];
        }
    }else{
            imageView.image = [UIImage imageNamed:@"占位图.png"];
        }
    
    
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 0.35, 100, 100, 30)];
    imageView.tag = 5002;
    lable.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lable];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(kWidth / 9.5, kHeight / 4.5, 100, 20);
    [button setTitle:@"登录" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    button.tag = 5001;
    lable.tag = 5000;
    lable.text = @"未登录";
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
#warning  约束----坐标
    button2.frame = CGRectMake(kWidth / 1.5, kHeight / 4.5, 100, 20);
    [button2 addTarget:self action:@selector(zhuxiaoAction) forControlEvents:UIControlEventTouchUpInside];
    [button2 setTitle:@"注销" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [view addSubview:button2];
    self.tableView.tableHeaderView = view;
    self.tableView.backgroundColor = [UIColor greenColor];
    self.tableView.separatorStyle = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [imageView addGestureRecognizer:tap];
    self.tableView.showsVerticalScrollIndicator = NO;
}
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请你选择要打开的图库" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
#warning 点击图片后要把图片给头像用   用户信息单例
    picker.allowsEditing = YES;
    UIImageView *imageView = [self.view viewWithTag:5002];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        //先把图片转化为NSData
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil) {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else{
            data = UIImagePNGRepresentation(image);
        }
        //图片保存的路径
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *imagePath = [path stringByAppendingPathComponent:@"image.png"];
        [data writeToFile:imagePath atomically:YES];
//        [fileManager createFileAtPath:imagePath contents:data attributes:nil];
//        [data writeToFile:imagePath atomically:YES];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        imageView.image = info[@"UIImagePickerControllerOriginalImage"];
              [self.tableView reloadData];
        [self dismissViewControllerAnimated:YES completion:nil];
       
    });
    
    
    
}
- (void)zhuxiaoAction
{
    NSString *buing = [[NSBundle mainBundle]bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:buing];
    UIButton *button = [self.view viewWithTag:5001];
    [button setTitle:@"登录" forState:UIControlStateNormal];
    UILabel *lable = [self.view viewWithTag:5000];
    lable.text = @"未登录";
    UIImageView *imageView = [self.view viewWithTag:5002];
    imageView.userInteractionEnabled = NO;
}
- (void)viewWillAppear:(BOOL)animated
{
    UILabel *lable = [self.view viewWithTag:5000];
//    UIImageView *imageView = [self.view viewWithTag:5002];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"uname"]) {
        UIImageView *imageView = [self.view viewWithTag:5002];
        imageView.userInteractionEnabled = YES;
        lable.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"uname"];
        UIButton *button = [self.view viewWithTag:5001];
        [button setTitle:@"已登录" forState:UIControlStateNormal];
//        imageView.image = [UIImage imageNamed:[[NSUserDefaults standardUserDefaults] objectForKey:@"头像"]];
    }
}
- (void)loginAction
{
    UIImageView *imageView = [self.view viewWithTag:5002];
    imageView.userInteractionEnabled = YES;
    YQLoginViewController *newVc = [YQLoginViewController new];
    [self presentViewController:newVc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  点击设置按钮
 *
 */
- (IBAction)didClickSetUpAction:(UIBarButtonItem *)sender {
    SetUpTableViewController *seuoVC = [SetUpTableViewController new];
    [self.navigationController pushViewController:seuoVC animated:YES];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    cell.textLabel.text = self.dataArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld",indexPath.row + 10]];
    if (indexPath.row == 0) {
        cell.backgroundColor = [UIColor cyanColor];
    }
    if (indexPath.row == 1) {
        cell.backgroundColor = [UIColor blueColor];
    }
    if (indexPath.row == 2) {
        cell.backgroundColor = [UIColor orangeColor];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChaXunViewController *cun = [ChaXunViewController new];
    cun.index = indexPath.row;
    [self.navigationController pushViewController:cun animated:YES];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
